//
//  MPOAuthController.swift
//  MPSinaWeibo
//
//  Created by DaVinci on 16/4/9.
//  Copyright © 2016年 DaVinci. All rights reserved.
//
//App Key：2769161420
//App Secret：591d2111b4e56b588ffe6903e6d2577f
//https://www.baidu.com

import UIKit
import SVProgressHUD


class MPOAuthController: UIViewController {

    
    let webView = UIWebView()
    
    override func loadView() {
        
        view = webView
        
        webView.delegate = self
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
       
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id="
        + client_id + "&redirect_uri=" + redirect_uri
        
        let urlRequest = NSURLRequest(URL: NSURL(string: urlString)!)
        webView.loadRequest(urlRequest)
        
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: nil, title: "关闭", target: self, action: "close")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: nil, title: "自动填充", target: self, action: "fullAccount")
    }
    
    
    override func viewWillDisappear(animated: Bool) {
        
        super.viewWillDisappear(animated)
        
        //隐藏HUD
        SVProgressHUD.dismiss()
    }
    
    
    @objc private func close(){
    
       dismissViewControllerAnimated(true, completion: nil)
    }
    
    //自动填充账号密码
    @objc private func fullAccount(){
    
       webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = '465056269@qq.com', document.getElementById('passwd').value = 'paris15358461971' ")
    
    }
}


extension MPOAuthController: UIWebViewDelegate{


    //MARK:webView代理方法
  
    
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
    }
   
    func webViewDidFinishLoad(webView: UIWebView) {
        
        
        let webtitle = webView.stringByEvaluatingJavaScriptFromString("document.title")
        
        title = webtitle
        
        SVProgressHUD.dismiss()

    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.URL?.absoluteString ?? ""
        
        let flag = "code="
        
        if urlString.containsString(flag){
        
            let range = urlString.rangeOfString(flag)!
            
            let code = urlString.substringFromIndex(range.endIndex)
            
           
            MPUserAccountViewModel.sharedAccountViewModel.loadAccessToken(code, finished: { (isSuccess) -> () in
                if !isSuccess {
                    //表示登录失败
                    SVProgressHUD.showErrorWithStatus("登录失败")
                    return
                }
                
                
                //TODO 跳转到欢迎页面
                // 单例对象的account 有值吗?  单例对象的模型没有赋值
                
                //跳转到欢迎页面 (用户名 + 用户头像)
                SVProgressHUD.showSuccessWithStatus("登录成功")
                
                self.dismissViewControllerAnimated(false, completion: { () -> Void in
                    
                    NSNotificationCenter.defaultCenter().postNotificationName(notificationName, object: nil)
                })
                
            })
            //不加载授权成功的回调页面
            return false
        }

            
            return true
    }
    
    

    
    
    
    
    }
    
//    func loadaccess_token(code: String){
//       
//        let urlString = "https://api.weibo.com/oauth2/access_token"
//        let parameters = ["client_id" : client_id, "client_secret" : client_secret, "grant_type" : "authorization_code", "code" : code, "redirect_uri" : redirect_uri]
//        
//        HMNetworkTools.sharedTools.request(.POST, urlString: urlString, parameters: parameters) { (result, error) -> () in
//            
//            if error != nil {
//            
//               return
//            }
//            
//            self.loadUserInfo(result!)
//        }
//    }
//    
//    
//    func loadUserInfo(result: AnyObject){
//    
//        let urlString = "https://api.weibo.com/2/users/show.json"
//        
//        guard let dict = result as? [String : AnyObject] else{
//        
//            return
//        }
//        
//        let access_token = dict["access_token"]!
//        let uid = dict["uid"]!
//        
//        let parameters = ["access_token" : access_token, "uid" : uid]
//        
//        HMNetworkTools.sharedTools.request(.GET, urlString: urlString, parameters: parameters) { (result, error) -> () in
//            
//            if error != nil {
//            
//               SVProgressHUD.showErrorWithStatus("数据出错啦")
//               return
//            }
//            
//            print(result)
//        }
//    
//        guard var userDict = result as? [String : AnyObject] else{
//        
//            SVProgressHUD.showErrorWithStatus("数据结构错误")
//            
//            return
//        }
//        
//        for(k,v) in dict{
//        
//            userDict[k] = v
//        }
//        
//        
//        //偏好设置不能保存nil
//        let userDefault = NSUserDefaults.standardUserDefaults()
//        
//        
//        let account = MPUserAccount(dict: userDict)
//        
//        let keys = ["access_token","avatar_large","name","expires_in","uid"]
//
//        let accountDict = account.dictionaryWithValuesForKeys(keys)
//        
//        userDefault.setObject(accountDict, forKey: userInfoKey)
//        
//        userDefault.synchronize()
//        
//        print(NSHomeDirectory())
//
//    }

